<template>
    
    <!-- 组件的模板 -->
    <div class="page__bd">
        <div class="weui-search-bar" id="searchBar">
            <form class="weui-search-bar__form">
                <div class="weui-search-bar__box">
                    <i class="weui-icon-search"></i>
                    <input type="search" class="weui-search-bar__input" id="searchInput" placeholder="搜索" required="">
                    <a href="javascript:" class="weui-icon-clear" id="searchClear"></a>
                </div>
                <label class="weui-search-bar__label" id="searchText" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1);" @click="toSearch">
                    <i class="weui-icon-search"></i>
                    <span>搜索</span>
                </label>
            </form>
        </div>
    </div>  
    <div class="page user-select multi-select">
      <scroller :lock-y="true" v-ref:scrollerdom>
        <div class="mod-crumbs bg-color scroller-wrap" v-show="hierarchyList.length>1">
          <template v-for="(index,hierarchy) in hierarchyList">
                <template v-if="index<(hierarchyList.length-1)">
                    <a class="nav-item" @click="stepHierarchy(index)">{{hierarchy.name}}</a>
                    <span class="arrow nav-item">&gt;</span>
                </template>
                <template v-if="index==(hierarchyList.length-1)">
                    <em class="nav-item">{{hierarchy.name}}</em>
                </template>
          </template>
        </div>
      </scroller>
      <ul class="list com-border-top com-border-bottom" style="margin-top: 0;">
            <li class="weui-cells_checkbox has-hierarchy"  v-for='group in grouplist'>
              <label class="touch" for="{{group.id}}">
                <div class="info com-border-bottom" :class="{'setHui':!group.action}" @click="selectGroup(group)">
                    <p class="title">{{group.name}}
                      <!-- <span :class="{'group_selected':group.children.length,'group_selected-next':group.children.length==0}" v-show="singleSelected">
                      </span> -->
                    </p>
                </div>
              </label>
              <div class="hierarchy" v-show="group.children.length" @click="stepNext(group.id)">下级</div>
            </li>
      </ul>
    </div>
     
</template>

<script>

    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import widget from 'gapi/widget'
    import cache from 'gapi/cache.js'
    import commonPage from 'clientApi/commonPage.js'
    import * as util from 'js/util.js'
    import GroupUtil from 'js/GroupUtil.js'
    import Scroller from 'vux/dist/components/scroller'
    import clientUi from 'gapi/clientUi.js'
    import KCApiApp from 'clientApi/KCApiApp.js'
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */
let pageDate = {}
let webViewID = ''
    /**
     *  组件实例对象
     */
    export default {
        components: {
          Scroller,
        },
        data: function(){
            return{
                group:{},
                hierarchyList:[],
                grouplist:[],
                cacheGroupList:[],
                singleSelected: false,
                type:'',
            }
        },
        watch: {
          'hierarchyList': function(){
            let allWidth = 0
            this.$nextTick(function () {
              if($('.scroller-wrap .nav-item').length){
                $('.scroller-wrap .nav-item').each(function(i, o){
                  if(o.tagName.toLowerCase() == 'a'){
                    allWidth += (parseInt(o.offsetWidth) + 16)
                  }else{
                    allWidth += parseInt(o.offsetWidth)
                  }
                })
                allWidth += 30
                $('.scroller-wrap').width(allWidth + 'px')

                this.$refs.scrollerdom.reset()
              }
            })
          }
        },
        computed: {
            
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
               /**
                * [获取地址参数  id 存在 则获取缓存中的小组列表以 不存在 则发起请求获取小组列表]
                *  cacheGroupList==> 保存小组列表数据
                *  participantGroup ==> 参与小组id 以,号分隔
                *  
                * @type {[type]}
                */ 
              
                cache.getMemoryCache('KqCacheMessge',(data)=>{
                    pageDate.project_id = data.project_id
                    pageDate.team_id = data.team_id 
                    pageDate.user_id = data.user_id
                    pageDate.type = data.type
                    pageDate.group_id = data.group_id
                    pageDate.id = util.getUrddataString('id')
                     if(pageDate.id){
                          cache.getMemoryCache('cacheGroupList', (data) => {
                              if(data){
                                  this.group = new GroupUtil(data)
                                  this.showGroup(pageDate.id,this.group.group)
                              }
                          })
                     }else{
                         this.getGroupList() 
                     }
                })
                 commonPage.getWebViewID((data)=>{ 
                    webViewID = data
                })
            },
            /**
             * 当选中小组时，判断该小组的子小组是否被选中，若有被选中的子小组，则清除掉
             * @param  {[type]} group [description]
             * @param  {[type]} event [description]
             * @return {[type]}       [description]
             */
            selectGroup(group){
                //埋点
                let statisticsLog_data = {
                    event_id: '选择小组页-点选小组',
                    // event_label: data.event_label,(预留，现在不用传此参数)
                    event_param: {
                        ca_from: 'selectgroup',
                        project_id: util.getUrddataString('projectId'),
                    }
                }
                KCApiApp.statisticsLog(statisticsLog_data)

                this.singleSelected = !this.singleSelected
                
                
                if(util.getUrddataString('is_move') === 'yes'){
                    let that = this;
                    let dialogtxt = '是否将已选人员移动到' + group.name + '小组？';
                    clientUi.showDialog(dialogtxt, '', function(data){
                        if(data.status == 1){
                            //埋点
                            let statisticsLog_data = {
                                event_id: '选择小组页-确定_弹层',
                                // event_label: data.event_label,(预留，现在不用传此参数)
                                event_param: {
                                    ca_from: 'sure',
                                    project_id: util.getUrddataString('projectId'),
                                }
                            }
                            KCApiApp.statisticsLog(statisticsLog_data)
                            that.ajaxpost(group.id)
                        }else{

                        }
                    },'确定','取消')                    
                    
                } else if(pageDate.type){
                    let that = this;
                    let dialogtxt = '是否将当前人员移动到' + group.name + '小组？';
                    clientUi.showDialog(dialogtxt, '', function(data){
                        if(data.status == 1){
                            //埋点
                            let statisticsLog_data = {
                                event_id: '选择小组页-确定_弹层',
                                // event_label: data.event_label,(预留，现在不用传此参数)
                                event_param: {
                                    ca_from: 'sure',
                                    project_id: util.getUrddataString('projectId'),
                                }
                            }
                            KCApiApp.statisticsLog(statisticsLog_data)
                            that.ajaxpostType(group.id)
                        }else{

                        }
                    },'确定','取消') 

                } else {
                  setTimeout(() => {
                    this.nextSelectgroup(group)
                }, 100)  
                }
                
            },
            ajaxpost(group_id){
                var str = util.getUrddataString('user_id') 
                var strs= new Array(); //定义一数组 
                strs = str.split(","); //字符分割
                util.ajax({
                    url:'/group/batch/member_change_relations',
                    type:'POST',
                    data:{
                        team_id: util.getUrddataString('teamId'),
                        project_id : util.getUrddataString('projectId'),
                        group_id : group_id,
                        user_id:JSON.stringify(strs)
                    },
                    timeout:10000,
                    success:(result) => {

                        // if(result.errno == 0){
                        //     widget.toast('移动成功');    
                        //     this.getAllGroupInfo()
                        //     cache.getMemoryCache('memberViewId',(data)=>{
                        //         if(data){
                        //           commonPage.goBack(1,{},data.webViewID)
                        //         }
                        //     })
                        // }

                        widget.toast('移动成功');    
                        cache.getMemoryCache('memberViewId',(data)=>{
                            if(data){
                              commonPage.goBack(1,{},data.webViewID)
                            }
                        })
                    },
                    error: (xhr, status) => {
                        // error
                        var toastStr = ''
                        if(status == 'timeout'){
                          toastStr = '网络请求超时'
                        }else{
                          toastStr = '服务器异常'
                        }
                        widget.toast(toastStr)
                    },
                    complete: () => {

                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            ajaxpostType(group_id){
                const data = {
                    team_id: pageDate.team_id,
                    project_id : pageDate.project_id,
                    current_group_id: pageDate.group_id,
                    target_group_id : group_id,
                    to_user_id:pageDate.user_id
                }
                util.ajax({
                    url:'/changestore/postion_apply',
                    type:'POST',
                    data,
                    timeout:10000,
                    success:(result) => {

                        // if(result.errno == 0){
                        //     widget.toast('移动成功');    
                        //     this.getAllGroupInfo()
                        //     cache.getMemoryCache('memberViewId',(data)=>{
                        //         if(data){
                        //           commonPage.goBack(1,{},data.webViewID)
                        //         }
                        //     })
                        // }

                        widget.toast('移动成功');    
                        cache.getMemoryCache('memberViewId',(data)=>{
                            if(data){
                              commonPage.goBack(1,{},data.webViewID)
                            }
                        })
                    },
                    error: (xhr, status) => {
                        // error
                        var toastStr = ''
                        if(status == 'timeout'){
                          toastStr = '网络请求超时'
                        }else{
                          toastStr = '服务器异常'
                        }
                        widget.toast(toastStr)
                    },
                    complete: () => {

                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            nextSelectgroup(group){
              if(group.action){
                let selectGroup = {'id':group.id,'name':group.name}
                cache.getMemoryCache('webViewID',(data)=>{
                    if(data){
                      commonPage.goBack(1,{'key':'selectGroup','value':selectGroup},data.webViewID)
                    }
                })
              }
            },


            /**
             * 跳转下一级
             * @param  {[type]}
             * @return {[type]}
             */
            stepNext(id){
                  if(util.getUrddataString('is_move')){
                      let encodeStr = encodeURIComponent(`id=${id}&teamId=${util.getUrddataString('teamId')}&projectId=${util.getUrddataString('projectId')}&user_id=${util.getUrddataString('user_id')}&is_move=yes`)
                      window.location.href = `dmsaas://GroupSelectSingle?urdData=${encodeStr}`
                  }else{
                      window.location.href="dmsaas://GroupSelectSingle?urdData="+encodeURIComponent(`id=${id}`)
                  }
                  
                  // window.location.href="http://192.168.45.155:8000/app/yy_kqgroupselect/yy_kqgroupselect.html?urdData="+encodeURIComponent(`id=${id}`)
            },
            /**
             * 点击对应层级 
             * 
             * @return {[type]}
             */
            stepHierarchy(index){
                let leg = this.hierarchyList.length-1
                if(index<leg){
                    cache.getMemoryCache('webViewID'+index,(data)=>{
                        if(data){
                           commonPage.goBack(1,{},data.webViewID)
                        }
                    })
                }
            },
            // 当前页面数据处理
            showGroup(id,list){
                  list.some((item)=>{
                    if(item.id==id){
                        this.hierarchyList = item.path
                        this.grouplist = item.children
                        let len = this.hierarchyList.length-1
                        cache.setMemoryCache('webViewID'+len,{'webViewID':webViewID})//保存当前页面唯一标识，点击面包屑使用
                        return true
                    }else{
                        this.showGroup(id,item.children)
                    }
                })
            },
            // 获取小组列表
            getGroupList(){
                commonPage.loadPageStatus('loading')
                util.ajax({
                    url: '/group/select_list',
                    data: {
                        team_id:pageDate.team_id,
                        project_id: pageDate.project_id,
                        group_id:''
                    },
                    success: (res) => {
                        console.log(res)
                        // res = JSON.parse(res)  
                        commonPage.loadPageStatus('loadSuccess')
                        if(res&&res.errno==0){
                            this.cacheGroupList = res.data
                            this.group = new GroupUtil(this.cacheGroupList)
                            this.hierarchyList = [{'id':'all','name':'全部'}]
                            this.grouplist = this.group.group
                            let allGroupList = this.group.formatGroup(this.group.group)
                            cache.setMemoryCache('allGroupList',allGroupList)
                            cache.setMemoryCache('cacheGroupList',this.cacheGroupList)
                            cache.setMemoryCache('webViewID0',{'webViewID':webViewID})
                        }else if(res.errmsg){
                             widget.toast(res.errmsg)
                        }else{
                             widget.toast('获取小组数据异常')
                        }
                        
                    },
                    error: (xhr, status) => {
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('服务器异常')

                    },
                    noNetwork: () => {
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            /**
             * 跳转搜索页
             * @return {}
             */
            toSearch(){
                window.location.href="dmsaas://GroupSearchSingle?urdData=" + encodeURIComponent(`type=${this.type}`)
            }
        },
        created(){
            this.init()
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/user-list.css"></style>

<style>
   
    .weui-cells_checkbox .setHui{
        color:#bbbbbb
    }
    .scroller-wrap .nav-item{
      float: left;
    }
    .mod-crumbs .arrow.nav-item{
    margin: 18px 8px;
  }
    .xs-container{
      background: #fff;
    }
</style>

